package com.smarthome.ipc;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smarthome.common.ipc.CommandExporter;
import com.smarthome.domain.ipc.IpcConstants;
import com.smarthome.domain.ipc.IpcResponse;

/**
 * ipc的接口网关入口。
 *
 *
 * @author KongXiangyu
 *
 * @since 1.0
 */
@Controller
@RequestMapping("/ipc")
public class IpcGateway {

    private static final Logger LOGGER = LoggerFactory.getLogger(IpcGateway.class);

    @RequestMapping(value = "/gateway.do", produces = { "text/json" }, method = { RequestMethod.GET, RequestMethod.POST })
    public void service(HttpServletRequest req, HttpServletResponse res) throws Exception {
        String reqStr = "";
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            params.put(name, req.getParameter(name));
            reqStr += name + "=" + req.getParameter(name) + "&";
        }
        LOGGER.info("收到请求消息1:" + reqStr);
//        parameterNames=req.getHeaderNames();
//        while (parameterNames.hasMoreElements()) {
//            String name = parameterNames.nextElement();
//            params.put(name, req.getHeader(name));
//            reqStr += name + "=" + req.getHeader(name) + "&";
//        }
//        LOGGER.info("收到请求消息2:" + reqStr);
        if (null != params && params.size() > 0) {
            String serviceName = params.get(IpcConstants.IPC_COMMAND_NAME);
            if (!StringUtils.isBlank(serviceName)) {
                IpcResponse<?> response = CommandExporter.doCommand(params);
                String responseStr = CommandExporter.parseJsonString(response, null);
                LOGGER.info("ipc-gateway-responseStr:" + responseStr);
                CommandExporter.sendResponse(responseStr, res);
            }
        }
    }

}
